package cn.com.dhcc.turbo.service.stat;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Categories;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Category;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Chart;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartDataset;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartSet;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartXmlUtil;
import cn.com.dhcc.app.pub.core.util.fusioncharts.NewChartXmlUtil;
import cn.com.dhcc.turbo.dao.stat.ExchStatManageDao;
import cn.com.dhcc.turbo.entity.stat.ExchStatManage;

@Service
public class ExchStatManageService extends BaseService {
	@Autowired
	private ExchStatManageDao dao; 
     
	/** 
	 * @param nt ,统计时间.
	 * @return
	 * @throws ServiceException
	 */
	 public String getStBtReg(String nt)throws ServiceException {
         String msg = "";
         try {
      	   List< ExchStatManage> exchStatManageList = null;
      	 List< ExchStatManage> exchStatMangeTime = null;
      	 exchStatManageList = dao.getStBtReg(nt);
      	   exchStatMangeTime=dao.getStBtRegTime(nt);
      	   
             
              Chart chart = new Chart();
              String extProperty = " palette='1' showLabels='1' plotgradientcolor='' canvasborderalpha='0' valuePadding='5'" +
              		" chartBottomMargin='5' chartLeftMargin='5' outCnvBaseFontSize='12' labeldisplay='STAGGER'  showplotborder='1' " +
              		"baseFontSize='12' showBorder='0' bgAlpha='0,0'    caption='"+nt+"  节点/适配器注册频次'   numberSuffix='次'  showvalues='0' ";
              		 
              chart.setExtProperty(extProperty);
             
              List< Category> cList = new ArrayList <Category >();
              Categories categories = new Categories();
              for(Iterator<ExchStatManage> iterator = exchStatMangeTime.iterator(); iterator.hasNext(); ) {
            	  ExchStatManage vo = iterator.next();
              	 
                  Category c0 = new Category(); 
           		   c0.setLabel(vo.getNT());
          	    
                  cList.add(c0);
              }
              categories.setCategory(cList);
              chart.setCategories(categories);
             
              List< ChartDataset> dList = new ArrayList <ChartDataset >();
              ChartDataset d1 = new ChartDataset();
              d1.setSeriesName("节点" );
              d1.setColor("167ed5" );
              List< ChartSet> sets1 = new ArrayList <ChartSet >();
              for(Iterator< ExchStatManage> iterator = exchStatManageList.iterator(); iterator.hasNext(); ) {
            	  ExchStatManage vo = iterator.next();
                  ChartSet set = new ChartSet(); 
                  
                  if(vo.getReg_type().equals("2")){
                  	set.setValue(vo.getNum());
                      sets1.add(set);
                  } 

              }
             
              ChartDataset d2 = new ChartDataset();
              d2.setSeriesName("适配器" );
              d2.setColor("ffce54" );
              List< ChartSet> sets2 = new ArrayList <ChartSet >();
              for(Iterator< ExchStatManage> iterator = exchStatManageList.iterator(); iterator.hasNext(); ) {
            	  ExchStatManage vo = iterator.next();
                  ChartSet set = new ChartSet();
                  if(vo.getReg_type().equals("1")){
                  	set.setValue(vo.getNum());
                      sets2.add(set);
                  } 
              }
             
              d1.setSet(sets1);
              d2.setSet(sets2);
              dList.add(d1);
              dList.add(d2);
              chart.setDataset(dList);
             
              msg = ChartXmlUtil.forXML(chart );
         } catch(DaoException e) {
              throw new ServiceException("数据统计失败", e);
         }
         return msg;
   }
	 
	 /**
		 * 节点间交换频率(月/年)
		 * @param nt 统计时间
		 * @param stat_level 统计级别： 1 节点  3 系统
		 * @param timeType
		 * @return
		 * @throws DaoException
		 */ 
	 public String getStBtNodeNum(String nt,String timeType,String stat_level)throws ServiceException {
         String msg = "";
         try {
        	 
        	 String slevel=""; 
        	 List<ExchStatManage> exchStatManageList = null; 
          	 List<ExchStatManage> exchStatNameList = null; 
          	 exchStatManageList = dao.getStBtNodeNum(timeType, stat_level, nt);
          	 
          	 List<ExchStatManage> sumList=new ArrayList<ExchStatManage>();
          	 for(int i=0;i<exchStatManageList.size();i++){
          		ExchStatManage vo=exchStatManageList.get(i);
          		int a=Integer.parseInt(vo.getFrom_num());
          		int b=Integer.parseInt(vo.getSend_num());
          		int sum=a+b; 
          		vo.setSumNum(sum+"");
          		sumList.add(vo);
          	 }
          	Collections.sort(sumList, new Comparator<ExchStatManage>(){
 
				public int compare(ExchStatManage o1, ExchStatManage o2) {
					int s1=Integer.parseInt(o1.getSumNum());
					int s2=Integer.parseInt(o2.getSumNum());
					if(s2>s1){
						return 1;
					} else if(s2==s1){
						return 0;
					}else {
						return -1;
					}
				}  
          	});
          	
         
          	 
          	 List<ExchStatManage> newlist=new ArrayList<ExchStatManage>();
          	for (ExchStatManage exch : sumList) {
    			if (!newlist.contains(exch) && !eq(newlist, exch)) {
    				newlist.add(exch);
    			}
    		} 
          	 
       	 
       	 if(stat_level.equals("1")){
       		slevel="节点间";
       	 exchStatNameList=dao.getStBtNodeNumName(timeType);
       	 if(newlist!=null&&!newlist.isEmpty()){
      		 for (ExchStatManage exch : exchStatNameList) {
      			 for (ExchStatManage exch1 : newlist) {
      				 if(exch.getFrom_id().equals(exch1.getFrom_id())){
      					 exch1.setFrom_name(exch.getFrom_name());
      					exch1.setTo_name(exch.getTo_name());
      					
      				 } 
				}
				
			}
      		 
      	 }
       	 } 
       	 if(stat_level.equals("3")){
       		slevel="适配器间";
       		exchStatNameList=dao.getStBtNodeNumSysName(timeType);
          	 if(newlist!=null&&!newlist.isEmpty()){
         		 for (ExchStatManage exch : exchStatNameList) {
         			 for (ExchStatManage exch1 : newlist) {
         				 if(exch.getFrom_id().equals(exch1.getFrom_id())){
         					 exch1.setFrom_name(exch.getFrom_name());
         					exch1.setTo_name(exch.getTo_name());
         					
         				 } 
   					
   				}
   				
   			}
         		 
         	 }
       		 
       	 }
      	

        Chart chart = new Chart();
        String extProperty = " palette='1' showLabels='0' plotgradientcolor='' canvasborderalpha='0' valuePadding='5' chartBottomMargin='5'" +
        		" chartLeftMargin='5' outCnvBaseFontSize='12' labeldisplay='STAGGER'  showplotborder='0' baseFontSize='12' showBorder='0' bgAlpha='0,0' " +
        		" maxColWidth='30'  caption='"+nt+" "+slevel+"交换频次(top10)'   numberSuffix='次' slantLabels='1' showSum='1'   showvalues='0'";
        		 
        chart.setExtProperty(extProperty);
       
        List< Category> cList = new ArrayList <Category >();
        Categories categories = new Categories();
        for(Iterator<ExchStatManage> iterator = newlist.iterator(); iterator.hasNext(); ) {
        	ExchStatManage vo = iterator.next();
        	 
            Category c0 = new Category(); 
     		   c0.setLabel(vo.getFrom_id());
    	    
            cList.add(c0);
        }
        categories.setCategory(cList);
        chart.setCategories(categories);
       
        List< ChartDataset> dList = new ArrayList <ChartDataset >();
        ChartDataset d1 = new ChartDataset();
        d1.setSeriesName("节点发送频次" );
        d1.setColor("167ed5" );
        d1.setIncludeInLegend("0");
        List< ChartSet> sets1 = new ArrayList <ChartSet >();
        for(Iterator< ExchStatManage> iterator = newlist.iterator(); iterator.hasNext(); ) {
        	    ExchStatManage vo = iterator.next();
                ChartSet set = new ChartSet();  
            	set.setValue(vo.getFrom_num());
            	set.setTooltext(vo.getFrom_name()+",发送:"+vo.getFrom_num()+"次");
                sets1.add(set); 
        }
       
        ChartDataset d2 = new ChartDataset();
        d2.setSeriesName("节点发送频次" );
        d2.setColor("ffce54" );
        d2.setIncludeInLegend("0");
        List< ChartSet> sets2 = new ArrayList <ChartSet >();
        for(Iterator< ExchStatManage> iterator = newlist.iterator(); iterator.hasNext(); ) {
        	ExchStatManage vo = iterator.next();
            ChartSet set = new ChartSet(); 
            	set.setValue(vo.getSend_num());
            	set.setTooltext(vo.getTo_name()+",发送:"+vo.getSend_num()+"次");
                sets2.add(set);
            
        }
       
        d1.setSet(sets1);
        d2.setSet(sets2);
        dList.add(d1);
        dList.add(d2);
        chart.setDataset(dList);
       
        msg = NewChartXmlUtil.forXML(chart );
      	 
      	  
             
             
         } catch(DaoException e) {
              throw new ServiceException("数据统计失败", e);
         }
         return msg;
   }
	 
	 
	 /**
		 * 内外网交换频率最高的业务数据（月/年）
		 * @param nt 统计时间
		 * @param stat_level 统计级别： 1 节点 2 业务域 3 系统
		 * @param timeType
		 * @return
		 * @throws DaoException
		 */ 
	public String getStBtNetTop(String nt,String timeType,String stat_level )throws ServiceException {
         String msg = "";
         try { 
      	   List< ExchStatManage> exchStatManageList = null; 
//      	 List< ExchStatManage> exchStatNameList = null; 
      	 exchStatManageList = dao.getStBtNetTop(timeType, stat_level, nt );
      	 
      	 List<ExchStatManage> sumList=new ArrayList<ExchStatManage>();
      	 for(int i=0;i<exchStatManageList.size();i++){
      		ExchStatManage vo=exchStatManageList.get(i);
      		vo.setSumNum((Integer.parseInt(vo.getFrom_num())+Integer.parseInt(vo.getSend_num()))+"");
      		sumList.add(vo);
      	 }
      	Collections.sort(sumList, new Comparator<ExchStatManage>(){ 
			public int compare(ExchStatManage o1, ExchStatManage o2) {
				int s1=Integer.parseInt(o1.getSumNum());
				int s2=Integer.parseInt(o2.getSumNum());
				if(s2>s1){
					return 1;
				} else if(s2==s1){
					return 0;
				}else {
					return -1;
				}  
			}  
      	});
      	
      	
      	

        Chart chart = new Chart();
        String extProperty = " palette='1' showLabels='0' plotgradientcolor='' canvasborderalpha='0' valuePadding='5' chartBottomMargin='5' " +
        		" chartLeftMargin='5' outCnvBaseFontSize='12' labeldisplay='STAGGER'  showplotborder='0' baseFontSize='12' showBorder='0' " +
        		" bgAlpha='0,0'  maxColWidth='30'  caption='"+nt+" 内外网交换频次(top10)'  numberSuffix='次' slantLabels='1' showSum='1'   showvalues='0'";
        		 
        chart.setExtProperty(extProperty);
       
        List< Category> cList = new ArrayList <Category >();
        Categories categories = new Categories();
        for(Iterator<ExchStatManage> iterator = sumList.iterator(); iterator.hasNext(); ) {
        	ExchStatManage vo = iterator.next();
        	 
            Category c0 = new Category(); 
     		   c0.setLabel(vo.getFrom_name());
            cList.add(c0);
        }
        categories.setCategory(cList);
        chart.setCategories(categories);
       
        List< ChartDataset> dList = new ArrayList <ChartDataset >();
        ChartDataset d1 = new ChartDataset();
        d1.setSeriesName("外网发送频次" );
        d1.setColor("167ed5" );
       // d1.setIncludeInLegend("0");
        List< ChartSet> sets1 = new ArrayList <ChartSet >();
        for(Iterator< ExchStatManage> iterator = sumList.iterator(); iterator.hasNext(); ) {
        	ExchStatManage vo = iterator.next();
            ChartSet set = new ChartSet(); 
             
            	set.setValue(vo.getSend_num());
            	set.setTooltext(vo.getTo_name()+"(外网发送):"+vo.getSend_num()+"次");
                sets1.add(set);
             

        }
       
        ChartDataset d2 = new ChartDataset();
        d2.setSeriesName("内网发送频次" );
        d2.setColor("ffce54" );
        //d2.setIncludeInLegend("0");
        List<ChartSet> sets2 = new ArrayList <ChartSet >();
        for(Iterator< ExchStatManage> iterator = sumList.iterator(); iterator.hasNext(); ) {
        	ExchStatManage vo = iterator.next();
            ChartSet set = new ChartSet();
             
            	set.setValue(vo.getFrom_num());
            	set.setTooltext(vo.getFrom_name()+"(内网发送):"+vo.getFrom_num()+"次");
                sets2.add(set);
            
        }
       
        d1.setSet(sets1);
        d2.setSet(sets2);
        dList.add(d1);
        dList.add(d2);
        chart.setDataset(dList);
       
        msg = NewChartXmlUtil.forXML(chart );
      	 
      	  
             
             
         } catch(DaoException e) {
              throw new ServiceException("数据统计失败", e);
         }
         return msg;
   }
	 
	 /**
		 * 交换频率最高的业务数据（月/年）
		 * @param nt 统计时间
		 * @param FROM_NODE_ID  from节点id ,TO_NODE_ID to节点id
		 * @param stat_level 统计级别：1 内外网 2 管理范围内 3 节点之间
		 * @param DATA_TYPE_ID 系统类型id
		 * @param timeType
		 * @return
		 * @throws DaoException
		 */ 
		 public String getStBtDtTop(String nt, String timeType,String to_node_id,String from_node_id,String stat_level) throws ServiceException {
				String msg="";
				try {
					List<ExchStatManage> getAllList = null;
					getAllList = dao.getStBtDtTop(timeType, from_node_id, to_node_id, stat_level, nt);
					 String addNew="";
					 if(from_node_id!=null&&!from_node_id.equals("")&&!to_node_id.equals("") && to_node_id!=null){
						
						 if (getAllList!=null && getAllList.size()>0) {
							 addNew=getAllList.get(0).getFrom_name()+"~"+getAllList.get(0).getTo_name();
						 }
					 }
					
					 Chart chart = new Chart(); 
					 
		             String extProperty = "palette='5' baseFontSize='12'  use3dlighting='0' showBorder='0'  bgAlpha='0,0'  showshadow='0' " +
		             		" caption='"+nt+" 交换频率最高的业务数据' subcaption='"+addNew+"' numberSuffix='次' ";
		             chart.setExtProperty(extProperty);
		             
		             
		             List<ChartDataset> dList = new ArrayList<ChartDataset>();
		 			ChartDataset d1 = new ChartDataset();
		 			
		             List<ChartSet> set1 = new ArrayList<ChartSet>(); 
						for (Iterator<ExchStatManage> iterator = getAllList.iterator(); iterator.hasNext();) {
							ExchStatManage vo =  iterator.next();
							ChartSet set = new ChartSet();
							set.setLabel(vo.getNode_name());
							set.setValue(vo.getNum());
							set1.add(set);
						}
						
						d1.setSet(set1); 
						dList.add(d1); 
						chart.setSet(set1);
						msg = ChartXmlUtil.forXML(chart);
		  
				} catch (DaoException e) {
					throw new ServiceException("数据统计失败", e);
				}
				
				return msg;
			}
	 
	  
	    /**
		 * 获取sysinfo信息；
		 * */
		public List<ExchStatManage> getSysInfos() throws NiceException {
			try {
				return dao.getSysInfos();
			}   catch (DaoException e) {
				throw new NiceException("获取数据源信息失败", e);
			}
		}
		 /**
		 * 获取sysinfo信息；
		 * */
		public List<ExchStatManage> getNodeInfos() throws NiceException {
			try {
				return dao.getNodeInfos();
			}   catch (DaoException e) {
				throw new NiceException("获取数据源信息失败", e);
			}
		}
		
	 
	 private boolean eq(List<ExchStatManage> list,ExchStatManage exch){
		if (list!=null && !list.isEmpty()) {
			 for (ExchStatManage exchStatManage : list) {
					if (exchStatManage.getFrom_id().equals(exch.getTo_id()) && exchStatManage.getTo_id().equals(exch.getFrom_id())) {
						return true;
					}
				}
		}
		 return false;
	 }
	 
}
